package com.nl.controller.web.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.CmppReplyInfo;
import com.nl.controller.web.bean.SmsContent;
import com.nl.controller.web.bean.SmsTemplateAttr;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.bean.TaskSynInfo;
import com.nl.controller.web.mapper.JzzwCheckMapper;
import com.nl.controller.web.mapper.SmsTemplateAttrMapper;
import com.nl.controller.web.mapper.SmsUpwardMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsUpwardService {
	@Autowired
	private SmsUpwardMapper smsUpwardMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private JzzwCheckMapper jzzwCheckMapper;
	@Autowired
	private SmsInterfaceJzzwService smsInterfaceJzzwService;
	@Autowired
	private SmsTemplateAttrMapper smsTemplateAttrMapper;
	@Autowired
	private SmsContentService smsContentService;	
	@Autowired
	private SmsTemplateCheckService smsTemplateCheckService;	
	@Autowired
	private SmsTemplateAttrService smsTemplateAttrService;
	
	
	private HashMap<String, String> cacheMap = new HashMap<>();
	public void upward(Map<String, String> map){    		
		List<CmppReplyInfo> cmppReplyInfos = smsUpwardMapper.checkCmpp();
		if (cmppReplyInfos != null && !cmppReplyInfos.isEmpty()) {
			for (CmppReplyInfo cmppReplyInfo : cmppReplyInfos) {
				String srcTerminalId = cmppReplyInfo.getSrcTerminalId();
				String msgContent = cmppReplyInfo.getMsgContent().trim();
				String rowId = cmppReplyInfo.getRowId();
				if (this.getCache(rowId)) {
				
				if (msgContent.indexOf("-")!=-1) {
					String[] split = msgContent.split("-");
					if (split.length == 3) {
						String flag = split[0].toUpperCase();
						String mgrId = split[1].trim();
						String mgrFlag = split[2].trim();
						if (srcTerminalId.startsWith("86")) {
							srcTerminalId = srcTerminalId.substring(2);
						}
						if ("BQ".equals(mgrFlag)) {
							log.info("mgrId"+mgrId+msgContent);
							String[] msisdns = commonService.templateNotice("1000000002");
							List<String> msisdn = Arrays.asList(msisdns);
							if (msisdn.contains(srcTerminalId)) {
								TaskSynInfo taskInfo = smsUpwardMapper.findTaskInfo(mgrId);
								if (taskInfo == null) {
									log.info("mgrId"+mgrId+msgContent);
									continue;
								}
								Map<String, Object> checkMap = new HashMap<String, Object>();
								if ("Y".equals(flag)) {
									map.put(rowId, "id");
									checkMap.put("checkMsg", "");
									checkMap.put("mgrId", mgrId);
									checkMap.put("checkResult","1");
								}else if ("N".equals(flag)) {
									map.put(rowId, "id");
									checkMap.put("checkMsg", "");
									checkMap.put("mgrId", mgrId);
									checkMap.put("checkResult","2");
								}
								if (checkMap!=null&&!checkMap.isEmpty()) {
									try {
										int templateCheck = jzzwCheckMapper.templateCheck(checkMap);
										log.info("项目:"+mgrId+"审核结果入表:"+(templateCheck == 1 ? "成功" : "失败"));
										//调用JZZW审核同步接口
										JSONObject checkMsg = new JSONObject();
										checkMsg.put("taskId", mgrId);
										checkMsg.put("checkMsg", "");
										if ("Y".equals(flag)) {
											checkMsg.put("checkResult","1");	
										}else if ("N".equals(flag)) {
											checkMsg.put("checkResult","2");
										}
										smsInterfaceJzzwService.checkResultSyn(checkMsg);
									} catch (Exception e) {
										log.error("短信上行审核出现异常"+mgrId+";EXCEPTION"+e.toString());
										e.printStackTrace();
									}
								}
							}
						}
						else if ("HY".equals(mgrFlag)) {
							SmsTemplateAttr smsTemplateAttr = smsTemplateAttrMapper.findTemplateAttrByMgrId(mgrId);
							if (null == smsTemplateAttr) {
								continue;
							}
							System.out.println(smsTemplateAttr.getCityId());
							List<SmsUsers> checkUsers =smsUpwardMapper.findCheckUsersbyDuty();
							List<SmsUsers> cityUsers =smsUpwardMapper.findCheckUsersbyCityId(smsTemplateAttr.getCityId());
							List<String> cityMsisdns = new ArrayList<String>();
							List<String> checkMsisdns = new ArrayList<String>();
							for (SmsUsers cityUser : cityUsers) {
								log.info("地市管理员"+cityUser.getMsisdn());
								cityMsisdns.add(cityUser.getMsisdn());//地市号码
							}
							for (SmsUsers checkUser : checkUsers) {
								log.info("系统管理员"+checkUser.getMsisdn());
								checkMsisdns.add(checkUser.getMsisdn());//系统号码
							}
							//待发表信息
							Map<String, Object> mapSend = new HashMap<String, Object>();
							if ("11".equals(smsTemplateAttr.getCityId())) {
								mapSend.put("sender", "106571103");
							}else {
								mapSend.put("sender", "106571102");
							}
							mapSend.put("result", -1);
							mapSend.put("cityId", smsTemplateAttr.getCityId());
							mapSend.put("mgrId", mgrId);
							mapSend.put("mgrName", smsTemplateAttr.getName());
							mapSend.put("cityExtId", smsTemplateAttr.getCityExtId());
							//查询项目操作人
							String operatorMsisdn = smsContentService.findOperatorMsisdn(mgrId);
							//地市审核回复
							if (!cityMsisdns.isEmpty() && cityMsisdns.contains(srcTerminalId)) {
								String remark;
								String state;
								//成功给系统审核人发
								if ("Y".equals(flag)) {
									map.put(rowId, rowId);
									StringBuffer sbf = new StringBuffer();
									String contents = smsTemplateAttr.getCityName()+"市项目:" + smsTemplateAttr.getName()+",项目编码为:"+mgrId+"-"+ "地市管理员:"/*+checkName*/+srcTerminalId+"已审核,";
									sbf.append(contents);
									//获取短信内容
									SmsContent smsContent=smsContentService.findContentByMgrId(mgrId);
									//判断新旧短信
									if(smsContent.getNewContent() == null||"".equals(smsContent.getNewContent())){
										sbf.append("短信内容如下 :"+smsContent.getContent());	
									}else{
										sbf.append("短信内容如下 :"+smsContent.getNewContent());	
									}
									sbf.append(";同意请回复:Y-"+mgrId+"-HY，不同意请回复:N-"+mgrId+"-HY");
									//发送系统管理员
									for (String string : checkMsisdns) {
										try {
											mapSend.put("receiver", string);
											mapSend.put("content", sbf.toString());
											int result1 = smsTemplateAttrService.insertSend(mapSend);
											String logString = result1==1 ? "短信发送成功" : "短信发送失败";
											log.info(logString+";短信内容为:"+sbf.toString());
										}
										catch (Exception e) {
											log.error("模板审核异常"+e.toString());
											e.printStackTrace();
										}
									}
									remark="通过";
									state="1";
									//失败返回失败信息给操作人
								}else if ("N".equals(flag)) {
									map.put(rowId, rowId);
									StringBuffer sBuffer = new StringBuffer();
									sBuffer.append("您好,项目:");
									sBuffer.append(smsTemplateAttr.getName());
									sBuffer.append("由"+srcTerminalId+"审核;");
									sBuffer.append("审核结果:失败;");
									int result=-1;
									try {									
										mapSend.put("receiver", operatorMsisdn);
										mapSend.put("content", sBuffer.toString());
										result = smsTemplateAttrService.insertSend(mapSend);
										String logString = result==1 ? "短信发送成功" : "短信发送失败";
										log.info(logString+";短信内容为:"+sBuffer.toString());
									}catch (Exception e) {
										log.error("短信发送失败;短信内容:"+sBuffer.toString());
										e.printStackTrace();
									}
									remark="不通过";
									state ="3";
								}else {
									continue ;
								}
								//修改审核状态，入审核记录表
								smsTemplateCheckService.templateCheckJK(mgrId,state,remark,srcTerminalId);
								//系统审核人审核回复
							}else if((!checkMsisdns.isEmpty() && checkMsisdns.contains(srcTerminalId))){
								String state;
								String remark;
								StringBuffer sBuffer = new StringBuffer();
								if ("Y".equals(flag)) {//同意
									map.put(rowId, rowId);
									sBuffer.append("您好,项目:");
									sBuffer.append(smsTemplateAttr.getName());
									sBuffer.append("由"+srcTerminalId+"审核;");
									sBuffer.append("审核结果:成功;");
									state ="2";
									remark="通过";
								}else if ("N".equals(flag)) {//不同意
									map.put(rowId, rowId);
									sBuffer.append("您好,项目:");
									sBuffer.append(smsTemplateAttr.getName());
									sBuffer.append("由"+srcTerminalId+"审核;");
									sBuffer.append("审核结果:失败;");
									state ="3";
									remark="不通过";
								}else {
									continue ;
								}
								try {
									mapSend.put("receiver", operatorMsisdn);
									mapSend.put("content", sBuffer.toString());
									//回复操作人
									int result1 = smsTemplateAttrService.insertSend(mapSend);
									String logString = result1==1 ? "短信发送成功" : "短信发送失败";
									log.info(logString+";短信内容为:"+sBuffer.toString());
									//修改审核状态，入审核记录表
									smsTemplateCheckService.templateCheckJK(mgrId,state,remark,srcTerminalId);
									mapSend.put("receiver", "15150690304");
									int result2 = smsTemplateAttrService.insertSend(mapSend);
									if(result2>0){
										log.info("项目编码："+mgrId+"，已审核,已短信通知系统管理员：15150690304。");
									}
									mapSend.put("receiver", "13905186970");
									int result3 = smsTemplateAttrService.insertSend(mapSend);
									if(result3>0){
										log.info("项目编码："+mgrId+"，已审核,已短信通知系统管理员：13905186970。");
									}
									
								}
								catch (Exception e) {
									log.error("模板审核异常"+e.toString());
									e.printStackTrace();
								}
							}																

						}
					}

				}

			}
		}
		}
	}
	 /**
     * 获取缓存的对象
     * 
     * @param rowId
     * @return
     */
    private boolean getCache(String rowId) {
        if (cacheMap.containsKey(rowId)) {
        	log.info("已有缓存："+rowId);
            return false;
        }
        cacheMap.put(rowId,rowId);
        log.info("新增缓存："+rowId);
        return true;
    }

}
